package com.numberone.master.modules.oa.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.numberone.master.common.persistence.Page;
import com.numberone.master.common.utils.Encodes;
import com.numberone.master.common.utils.StringUtils;
import com.numberone.master.common.web.BaseController;
import com.numberone.master.modules.oa.entity.Delayed;
import com.numberone.master.modules.oa.entity.File;
import com.numberone.master.modules.oa.entity.Operation;
import com.numberone.master.modules.oa.entity.ProcessingFlow;
import com.numberone.master.modules.oa.entity.WorkOrder;
import com.numberone.master.modules.oa.service.DelayedService;
import com.numberone.master.modules.oa.service.OperationService;
import com.numberone.master.modules.oa.service.WorkOrderService;
import com.numberone.master.modules.sys.entity.User;
import com.numberone.master.modules.sys.service.OfficeService;
import com.numberone.master.modules.sys.service.SystemService;
import com.numberone.master.modules.sys.utils.DictUtils;
import com.numberone.master.modules.sys.utils.UserUtils;
import com.numberone.master.modules.sys.service.ComplainService;

@Controller
@RequestMapping(value = "${adminPath}/oa/workOrder")
public class WorkOrderController extends BaseController {
	
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private WorkOrderService workOrderService;
	
	@Autowired
	private ComplainService complainService;
	
	@Autowired
	private OperationService operationService;
	
	@Autowired
	private OfficeService officeService;
	
	@Autowired
	private DelayedService delayedService;
	
	@ModelAttribute
	public WorkOrder get(@RequestParam(required=false) String id) {
		
		
		WorkOrder entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workOrderService.get(id);
		}
		if (entity == null){
			entity = new WorkOrder();
		}
		return entity;
	}
	
/*	@ModelAttribute
	public User get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return systemService.getUser(id);
		}else{
			return new User();
		}
	}*/
	
	@RequestMapping(value = "self")
	public String selfList(HttpServletRequest request, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		WorkOrder workOrder = new WorkOrder();
		workOrder.setBelong(currentUser.getId());
		Page<WorkOrder> page = workOrderService.findList(new Page<WorkOrder>(request, response),workOrder);
		model.addAttribute("page", page);
		return "modules/oa/workOrderList";
		
	}
	
	@RequestMapping(value = "allList")
	public String findAllList(WorkOrder workOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		/*@SuppressWarnings("unchecked")
		Map<String, String[]> map = request.getParameterMap();
		for(Map.Entry<String, String[]> entry :map.entrySet()){
			System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()[0]);
		}*/
		Page<WorkOrder> page = workOrderService.findAllList(new Page<WorkOrder>(request, response),currentUser.getId(), workOrder);
		model.addAttribute("page", page);
		return "modules/oa/workOrderAllList";
		
	}
	
	@RequestMapping(value = "pool")
	public String findPool(WorkOrder workOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		/*@SuppressWarnings("unchecked")
		Map<String, String[]> map = request.getParameterMap();
		for(Map.Entry<String, String[]> entry :map.entrySet()){
			System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()[0]);
		}*/
		workOrder.setBelong(currentUser.getOffice().getId());
		System.out.println(workOrder.toString());
		Page<WorkOrder> page = workOrderService.findPoolList(new Page<WorkOrder>(request, response), workOrder);
		model.addAttribute("page", page);
		return "modules/oa/workOrderPool";
		
	}
	
	@RequestMapping(value = "form")
	public String form(WorkOrder workOrder, Model model) {
		List<Operation> operationList = operationService.findList(workOrder.getId());
		/*	List<File> fileList = new ArrayList<File>();
		String fileUrls = workOrder.getFiles();
		if(fileUrls != null){
			String[] fileArr = fileUrls.split("\\|");
			for (int i = 0; i < fileArr.length; i++) {
				if(i>0){
					String fileUrl = fileArr[i];
					File file = new File();
					file.setUrl(fileUrl);
					String[] fileName = fileUrl.split("/");
					if(fileName.length>6){
						file.setName(fileName[fileName.length-1]);
						User u = systemService.getUser(fileName[fileName.length-6]);
						file.setUserName(u.getName());
						fileList.add(file);
					}
					
				}
			}
			model.addAttribute("fileList", fileList);
		}*/
		model.addAttribute("workOrder", workOrder);
		model.addAttribute("operationList", operationList);
		return "modules/oa/workOrderForm";
	}
	
	@RequestMapping(value = "show")
	public String show(WorkOrder workOrder, Model model,RedirectAttributes redirectAttributes) {
		List<Operation> operationList = operationService.findList(workOrder.getId());
		List<File> fileList = new ArrayList<File>();
		String fileUrls = workOrder.getFiles();
		if(fileUrls != null){
			String[] fileArr = fileUrls.split("\\|");
			for (int i = 0; i < fileArr.length; i++) {
				if(i>0){
					String fileUrl = fileArr[i];
					File file = new File();
					file.setUrl(fileUrl);
					String[] fileName = fileUrl.split("/");
					file.setName(fileName[fileName.length-1]);
					fileList.add(file);
				}
				
			}
			model.addAttribute("fileList", fileList);
		}
		User currentUser = UserUtils.getUser();
		List<ProcessingFlow> pfList = workOrderService.getProcessingFlow(workOrder, currentUser);
		if(pfList!=null){
			model.addAttribute("pfList", pfList);
		}else{
			addMessage(redirectAttributes, "请求失败！");
		}
		model.addAttribute("workOrder", workOrder);
		model.addAttribute("operationList", operationList);
		return "modules/oa/workOrderShow";
	}
	
	@RequestMapping(value = "save")
	public String save(WorkOrder workOrder, Model model) {
		User currentUser = UserUtils.getUser();
		workOrder.setTransactor(currentUser.getId());
		workOrder.setFinishDate(new Date());
		workOrderService.update(workOrder);
		return "redirect:" + adminPath + "/oa/workOrder/self?repage";
	}
	
	//领取工单
	@RequestMapping(value = "receive")
	public String receive(WorkOrder workOrder, Model model, RedirectAttributes redirectAttributes) {
		User currentUser = UserUtils.getUser();
		Date date = new Date();
		
		
		//设置处理时限
		if(!StringUtils.isEmpty(workOrder.getProcessingTime2())){
			int hour = Integer.parseInt(workOrder.getProcessingTime2());
			Calendar cal = Calendar.getInstance();   
	        cal.setTime(date); 
	        cal.add(Calendar.HOUR, hour);// 24小时制   
	        date = cal.getTime();  
			workOrder.setProcessingTime(date);
		}else{
			String processingTime1 = DictUtils.getDictValue("通用", "processing_time1", "24");
			String processingTime2 = DictUtils.getDictValue("通用", "processing_time2", "3");
			workOrder.setProcessingTime1(processingTime1);
			workOrder.setProcessingTime2(processingTime2);
			int hour = Integer.parseInt(processingTime2);
			Calendar cal = Calendar.getInstance();   
	        cal.setTime(date); 
	        cal.add(Calendar.HOUR, hour);// 24小时制   
	        date = cal.getTime();  
			workOrder.setProcessingTime(date);
		}
		Operation operation = new Operation();
		operation.setOperationUser(currentUser.getName());
		operation.setOperationNo(currentUser.getNo());
		operation.setWorkOrderId(workOrder.getId());
		operation.setOperationName("领取工单");
		operation.setOperationTime(new Date());
		operation.setSendTo(currentUser.getName());
		System.out.println(workOrder.getBelong());
		System.out.println(StringUtils.isEmpty(workOrder.getBelong()));
		
		if(StringUtils.isEmpty(workOrder.getBelong())){
			workOrder.setState("2");
			workOrder.setBelong(currentUser.getId());
			if(workOrderService.receive(workOrder,currentUser)){
				operation.setContent("领取成功！");
				workOrderService.update(workOrder);
				operationService.insert(operation);
				addMessage(redirectAttributes, "领取成功！");
			}else{
				operation.setContent("领取失败！");
				addMessage(redirectAttributes, "领取失败！");
			}
		}else{
			workOrder.setState("2");
			workOrder.setBelong(currentUser.getId());
			operation.setContent("领取成功！");
			workOrderService.update(workOrder);
			operationService.insert(operation);
			addMessage(redirectAttributes, "领取成功！");
		}
		
		return "redirect:" + adminPath + "/oa/workOrder/pool";
		
	}
	
	//释放工单
	@RequestMapping(value = "sendBack")
	public String sendBack(WorkOrder workOrder, Model model){
		
		User currentUser = UserUtils.getUser();
		workOrder.setBelong("");
		workOrder.setState("1");
		Operation operation = new Operation();
		operation.setOperationUser(currentUser.getName());
		operation.setOperationNo(currentUser.getNo());
		operation.setWorkOrderId(workOrder.getId());
		operation.setOperationName("释放工单");
		operation.setOperationTime(new Date());
		operation.setSendTo("工单池");
		operation.setContent(workOrder.getResult());
		operationService.insert(operation);
		workOrderService.update(workOrder);
		return "redirect:" + adminPath + "/oa/workOrder/self";
	}
	
	//回复工单
	@RequestMapping(value = "reply")
	public String reply(WorkOrder workOrder, Model model,RedirectAttributes redirectAttributes){
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		java.util.Date date=new java.util.Date();  
		String str=sdf.format(date); 
		User currentUser = UserUtils.getUser();
		workOrder.setIssueEliminatTime(str);
		workOrder.setNdeptContact(currentUser.getName());
		workOrder.setNdeptContactPhone(currentUser.getPhone());
		workOrder.setState("4");
		workOrder.setProcessingTime(date);
		Operation operation = new Operation();
		operation.setOperationUser(currentUser.getName());
		operation.setOperationNo(currentUser.getNo());
		operation.setWorkOrderId(workOrder.getId());
		operation.setOperationName("回复工单");
		operation.setOperationTime(date);
		operation.setSendTo("在线客服");
		if(workOrderService.reply(workOrder,currentUser)){
			operation.setContent(workOrder.getDealResult());
			workOrderService.updateReply(workOrder);
			addMessage(redirectAttributes, "回复成功！");
		}else{
			operation.setContent("回复失败！");
			addMessage(redirectAttributes, "回复失败！");
		}
		operationService.insert(operation);
		return "redirect:" + adminPath + "/oa/workOrder/self";
	}
	
	//转发工单
	@RequestMapping(value = "transmit")
	public String transmit(WorkOrder workOrder, Model model){
		
		Operation operation = new Operation();
		User currentUser = UserUtils.getUser();
		Date date = new Date();
		StringBuilder belong = new StringBuilder(workOrder.getBelong());
		//设置处理时限
		int hour = Integer.parseInt(workOrder.getProcessingTime2());
		Calendar cal = Calendar.getInstance();   
        cal.setTime(date); 
        cal.add(Calendar.HOUR, hour);// 24小时制   
        date = cal.getTime();  
		workOrder.setProcessingTime(date);
		
		if(belong.indexOf("ut_") == -1){
			operation.setSendTo(officeService.get(belong.toString()).getName());
			workOrder.setBelong(belong.toString());
			workOrder.setState("3");
		}else {
			belong.delete(0, 3);
			operation.setSendTo(systemService.getUser(belong.toString()).getName());
			workOrder.setBelong(belong.toString());
			workOrder.setState("2");
		}
		
		workOrder.setNdeptContact(currentUser.getName());
		workOrder.setNdeptContactPhone(currentUser.getPhone());
		
		operation.setOperationUser(currentUser.getName());
		operation.setOperationNo(currentUser.getNo());
		operation.setWorkOrderId(workOrder.getId());
		operation.setOperationName("转发工单");
		operation.setOperationTime(new Date());
		operation.setContent(workOrder.getResult());
		
		operationService.insert(operation);
		workOrderService.update(workOrder);
		return "redirect:" + adminPath + "/oa/workOrder/self";
	}
	
	//阶段回复
	@RequestMapping(value = "stageReply")
	public String stageReply(WorkOrder workOrder, Model model,RedirectAttributes redirectAttributes){
		
		Date date = new Date();
		Operation operation = new Operation();
		User currentUser = UserUtils.getUser();
		operation.setSendTo("在线客服");
		operation.setOperationUser(currentUser.getName());
		operation.setOperationNo(currentUser.getNo());
		operation.setWorkOrderId(workOrder.getId());
		operation.setOperationName("阶段回复");
		operation.setOperationTime(date);
		if(workOrderService.stageReply(workOrder,currentUser)){
			operation.setContent(workOrder.getResult());
			addMessage(redirectAttributes, "回复成功！");
		}else {
			operation.setContent("回复失败！");
			addMessage(redirectAttributes, "回复失败！");
		}
		operationService.insert(operation);
		return "redirect:" + adminPath + "/oa/workOrder/form?id="+workOrder.getId();
	}
	
	//延时申请
	@RequestMapping(value = "delayApplication")
	public String delayApplication(WorkOrder workOrder, Model model){
		
		Date date = new Date();
		Operation operation = new Operation();
		Delayed delayed = new Delayed();
		User currentUser = UserUtils.getUser();
		StringBuilder belong = new StringBuilder(workOrder.getBelong());
		
		if(belong.indexOf("ut_") == -1){
			operation.setSendTo(officeService.get(belong.toString()).getName());
		}else {
			belong.delete(0, 3);
			delayed.setDispose(belong.toString());
			operation.setSendTo(systemService.getUser(belong.toString()).getName());
		}
		
		delayed.setApplicant(currentUser.getId());
		delayed.setApplicantDate(date);
		delayed.setReason(workOrder.getResult());
		delayed.setWorkOrderId(workOrder.getId());
		delayed.setState("1");
		
		operation.setOperationUser(currentUser.getName());
		operation.setOperationNo(currentUser.getNo());
		operation.setWorkOrderId(workOrder.getId());
		operation.setOperationName("延时申请");
		operation.setOperationTime(date);
		operation.setContent(workOrder.getResult());
		
		delayedService.insert(delayed);
		operationService.insert(operation);
		return "redirect:" + adminPath + "/oa/workOrder/form?id="+workOrder.getId();
	}
	
	//上传附件
	@RequestMapping(value = "uploadFile")
	public String uploadFile(WorkOrder workOrder, Model model){
		//url解码
		String fileUrl = Encodes.urlDecode(workOrder.getFiles());
		workOrder.setFiles(fileUrl);
		workOrderService.updateFiles(workOrder);
		
		User currentUser = UserUtils.getUser();
		Operation operation = new Operation();
		operation.setOperationUser(currentUser.getName());
		operation.setOperationNo(currentUser.getNo());
		operation.setWorkOrderId(workOrder.getId());
		operation.setOperationName("上传附件");
		operation.setOperationTime(new Date());
		operation.setSendTo(currentUser.getName());
		
		String fileNames = "";
		String[] fileArr = fileUrl.split("\\|");
		for (String file : fileArr) {
			String[] fileName = file.split("/");
			fileNames = "  " + fileNames + fileName[fileName.length-1] ;
		}
		operation.setContent(fileNames);
		operationService.insert(operation);
		return "redirect:" + adminPath + "/oa/workOrder/form?id="+workOrder.getId();
	}
	
	//驳回客服
	@RequestMapping(value = "reject")
	public String reject(WorkOrder workOrder, Model model,RedirectAttributes redirectAttributes){
		
		Date date = new Date();
		Operation operation = new Operation();
		User currentUser = UserUtils.getUser();
		operation.setSendTo("在线客服");
		operation.setOperationUser(currentUser.getName());
		operation.setOperationNo(currentUser.getNo());
		operation.setWorkOrderId(workOrder.getId());
		operation.setOperationName("驳回客服");
		operation.setOperationTime(date);
		workOrder.setState("6");
		if(workOrderService.reject(workOrder,currentUser)){
			operation.setContent(workOrder.getResult());
			workOrderService.update(workOrder);
			addMessage(redirectAttributes, "成功驳回！");
		}else{
			operation.setContent("驳回失败！");
			addMessage(redirectAttributes, "驳回失败！");
		}
		operationService.insert(operation);
		return "redirect:" + adminPath + "/oa/workOrder/self";
	} 
	
	//查询客服流程
	@RequestMapping(value = "getProcessingFlow")
	public String getProcessingFlow(WorkOrder workOrder, Model model,RedirectAttributes redirectAttributes){
		User currentUser = UserUtils.getUser();
		List<ProcessingFlow> pfList = workOrderService.getProcessingFlow(workOrder, currentUser);
		if(pfList!=null){
			model.addAttribute("pfList", pfList);
		}
		addMessage(redirectAttributes, "请求失败！");
		return "redirect:" + adminPath + "/oa/workOrder/show?id="+workOrder.getId();
	}
	
	//追回
	@RequestMapping(value = "getBack")
	public String getBack(WorkOrder workOrder, Model model,RedirectAttributes redirectAttributes){
		User currentUser = UserUtils.getUser();
		String message = workOrderService.getBack(workOrder,currentUser);
		addMessage(redirectAttributes, message);
		return "redirect:" + adminPath + "/oa/workOrder/allList";
	}
	
	//问题收集
	@RequestMapping(value = "problemCollection")
	public String problemCollection(WorkOrder workOrder, Model model,RedirectAttributes redirectAttributes){
		
		Date date = new Date();
		Operation operation = new Operation();
		User currentUser = UserUtils.getUser();
		operation.setSendTo("在线客服");
		operation.setOperationUser(currentUser.getName());
		operation.setOperationNo(currentUser.getNo());
		operation.setWorkOrderId(workOrder.getId());
		operation.setOperationName("问题收集");
		operation.setOperationTime(date);
		if(workOrderService.problemCollection(workOrder,currentUser)){
			operation.setContent(workOrder.getResult());
			addMessage(redirectAttributes, "收集成功！");
		}else {
			operation.setContent("收集失败！");
			addMessage(redirectAttributes, "收集失败！");
		}
		operationService.insert(operation);
		return "redirect:" + adminPath + "/oa/workOrder/form?id="+workOrder.getId();
	}
	
}
